using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MauiBuilder.Services;
using System.Timers;

namespace MauiBuilder.ViewModels
{
    /// <summary>
    /// 前台服务页面的视图模型
    /// 专门管理前台服务的启动、停止和状态监控功能
    /// </summary>
    public partial class ForegroundServiceViewModel : BaseViewModel
    {
        private readonly IForegroundService _foregroundService;
        private readonly LogManager _logManager = LogManager.Instance;
        private System.Timers.Timer _updateTimer;
        
        [ObservableProperty]
        private bool _isServiceRunning = false;
        
        [ObservableProperty]
        private string _serviceStatusMessage = "前台服务未运行";
        
        [ObservableProperty]
        private DateTime _lastStartTime = DateTime.MinValue;
        
        [ObservableProperty]
        private string _notificationCount = "0";

        public ForegroundServiceViewModel(IForegroundService foregroundService)
        {
            _foregroundService = foregroundService ?? throw new ArgumentNullException(nameof(foregroundService));
            _logManager.LogInfo("ForegroundServiceViewModel 初始化完成");
            
            // 初始化定时器，每秒更新一次时间显示
            _updateTimer = new System.Timers.Timer(1000); // 1秒间隔
            _updateTimer.Elapsed += OnTimerElapsed;
            
            // 同步真实的服务状态
            SyncServiceStatus();
            
            // 订阅服务状态变化事件
            _foregroundService.ServiceStateChanged += OnServiceStateChanged;
        }

        #region 计算属性

        /// <summary>
        /// 启动服务按钮文本
        /// </summary>
        public string StartServiceButtonText => IsServiceRunning ? "服务运行中" : "启动前台服务";

        /// <summary>
        /// 启动服务按钮是否可用
        /// </summary>
        public bool IsStartServiceEnabled => !IsServiceRunning;

        /// <summary>
        /// 停止服务按钮是否可用
        /// </summary>
        public bool IsStopServiceEnabled => IsServiceRunning;

        /// <summary>
        /// 服务状态颜色
        /// </summary>
        public Color ServiceStatusColor => IsServiceRunning ? Colors.Green : Colors.Red;

        /// <summary>
        /// 服务运行时长文本
        /// </summary>
        public string ServiceDurationText
        {
            get
            {
                if (!IsServiceRunning || LastStartTime == DateTime.MinValue)
                    return "服务未运行";
                
                var duration = DateTime.Now - LastStartTime;
                return $"已运行: {duration.Hours:D2}:{duration.Minutes:D2}:{duration.Seconds:D2}";
            }
        }

        /// <summary>
        /// 预计通知数量
        /// </summary>
        public string EstimatedNotificationsText
        {
            get
            {
                if (!IsServiceRunning || LastStartTime == DateTime.MinValue)
                    return "预计通知: 0 条";
                
                var duration = DateTime.Now - LastStartTime;
                var estimatedCount = (int)(duration.TotalSeconds / 5); // 每5秒一条通知
                return $"预计通知: {estimatedCount} 条";
            }
        }

        #endregion

        #region 命令

        /// <summary>
        /// 启动前台服务命令
        /// </summary>
        [RelayCommand]
        private async Task OnStartServiceAsync()
        {
            try
            {
                await _foregroundService.StartServiceAsync();
                IsServiceRunning = true;
                LastStartTime = DateTime.Now;
                ServiceStatusMessage = "前台服务已启动，正在发送定时通知";
                
                // 启动定时器实时更新运行时间
                _updateTimer?.Start();
                
                // 更新计算属性
                RefreshAllProperties();

                await AppShell.DisplayAlertAsync(
                    "✅ 服务启动成功", 
                    "前台服务已启动，将每5秒发送一次通知\n\n📋 重要提醒：\n• 请确保已允许应用发送通知\n• 检查手机是否开启免打扰模式\n• 确认未禁用应用通知权限\n• 服务将在后台持续运行", 
                    "我知道了");
                    
                _logManager.LogInfo("用户启动了前台服务");
            }
            catch (Exception ex)
            {
                _logManager.LogError($"启动前台服务失败: {ex.Message}");
                _logManager.LogError(ex.ToString());
                ServiceStatusMessage = $"启动失败: {ex.Message}";
                
                await AppShell.DisplayAlertAsync(
                    "❌ 启动失败", 
                    $"前台服务启动失败\n\n错误详情:\n{ex.Message}\n\n💡 解决建议:\n• 检查应用权限设置\n• 重启应用后重试\n• 确认设备支持前台服务", 
                    "确定");
            }
        }

        /// <summary>
        /// 停止前台服务命令
        /// </summary>
        [RelayCommand]
        private async Task OnStopServiceAsync()
        {
            try
            {
                bool confirm = await AppShell.DisplayConfirmAsync(
                    "⚠️ 确认停止服务", 
                    "确定要停止前台服务吗？\n\n停止后将不再发送定时通知。", 
                    "停止服务", 
                    "继续运行");
                    
                if (!confirm) return;
                
                await _foregroundService.StopServiceAsync();
                IsServiceRunning = false;
                ServiceStatusMessage = "前台服务已停止";
                
                // 停止定时器
                _updateTimer?.Stop();
                
                // 更新计算属性
                RefreshAllProperties();

                await AppShell.DisplayAlertAsync(
                    "✅ 服务已停止", 
                    "前台服务已成功停止\n\n通知发送已暂停", 
                    "确定");
                    
                _logManager.LogInfo("用户停止了前台服务");
            }
            catch (Exception ex)
            {
                _logManager.LogError("停止前台服务失败", ex);
                await AppShell.DisplayAlertAsync(
                    "❌ 停止失败", 
                    $"停止服务时发生错误:\n{ex.Message}", 
                    "确定");
            }
        }

        /// <summary>
        /// 刷新服务状态命令
        /// </summary>
        [RelayCommand]
        private void OnRefreshStatus()
        {
            SyncServiceStatus();
            OnPropertyChanged(nameof(ServiceDurationText));
            OnPropertyChanged(nameof(EstimatedNotificationsText));
            
            _logManager.LogInfo("用户刷新了服务状态");
        }

        /// <summary>
        /// 查看服务详情命令
        /// </summary>
        [RelayCommand]
        private async Task OnViewServiceDetails()
        {
            var details = $"🔧 前台服务详细信息\n\n" +
                         $"📊 当前状态: {(IsServiceRunning ? "运行中" : "已停止")}\n" +
                         $"⏰ 通知间隔: 5秒\n" +
                         $"🔔 通知类型: 系统通知\n" +
                         $"🎯 服务目的: 定时提醒\n" +
                         $"⚡ 电池影响: 极低\n\n";
                         
            if (IsServiceRunning)
            {
                details += $"🚀 启动时间: {LastStartTime:yyyy-MM-dd HH:mm:ss}\n" +
                          $"⏱️ {ServiceDurationText}\n" +
                          $"📨 {EstimatedNotificationsText}";
            }
            else
            {
                details += "💤 服务当前处于停止状态";
            }

            await AppShell.DisplayAlertAsync("服务详情", details, "确定");
        }

        /// <summary>
        /// 导航到通知页面命令
        /// </summary>
        [RelayCommand]
        private async Task OnNavigateToNotifications()
        {
            try
            {
                await Shell.Current.GoToAsync("//NotificationPage");
                _logManager.LogInfo("从前台服务页面导航到通知页面");
            }
            catch (Exception ex)
            {
                _logManager.LogError($"导航到通知页面失败: {ex.Message}");
                _logManager.LogError(ex.ToString());
                await AppShell.DisplayAlertAsync("导航错误", $"无法打开通知页面: {ex.Message}", "确定");
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 定时器事件处理，实时更新运行时间显示
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void OnTimerElapsed(object? sender, System.Timers.ElapsedEventArgs e)
        {
            if (IsServiceRunning)
            {
                // 在主线程中更新UI
                MainThread.BeginInvokeOnMainThread(() =>
                {
                    OnPropertyChanged(nameof(ServiceDurationText));
                    OnPropertyChanged(nameof(EstimatedNotificationsText));
                });
            }
        }

        /// <summary>
        /// 同步服务状态与实际运行状态
        /// </summary>
        private void SyncServiceStatus()
        {
            try
            {
                var actualServiceRunning = _foregroundService.IsServiceRunning();
                
                if (actualServiceRunning != IsServiceRunning)
                {
                    IsServiceRunning = actualServiceRunning;
                    
                    if (actualServiceRunning)
                    {
                        // 服务正在运行，但我们不知道具体的启动时间
                        // 设置为当前时间作为估计时间（不完全准确，但比没有好）
                        if (LastStartTime == DateTime.MinValue)
                        {
                            LastStartTime = DateTime.Now.AddMinutes(-1); // 假设1分钟前启动
                        }
                        
                        ServiceStatusMessage = "前台服务正在运行（已同步）";
                        _updateTimer?.Start();
                    }
                    else
                    {
                        ServiceStatusMessage = "前台服务未运行";
                        _updateTimer?.Stop();
                    }
                    
                    // 更新所有计算属性
                    RefreshAllProperties();
                    
                    _logManager.LogInfo($"服务状态已同步：{(actualServiceRunning ? "运行中" : "已停止")}");
                }
            }
            catch (Exception ex)
            {
                _logManager.LogError($"同步服务状态失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 服务状态变化事件处理
        /// </summary>
        /// <param name="isRunning">服务是否运行</param>
        private void OnServiceStateChanged(bool isRunning)
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                IsServiceRunning = isRunning;
                
                if (isRunning)
                {
                    if (LastStartTime == DateTime.MinValue)
                    {
                        LastStartTime = DateTime.Now;
                    }
                    ServiceStatusMessage = "前台服务正在运行";
                    _updateTimer?.Start();
                }
                else
                {
                    ServiceStatusMessage = "前台服务已停止";
                    _updateTimer?.Stop();
                }
                
                RefreshAllProperties();
                _logManager.LogInfo($"服务状态事件处理：{(isRunning ? "运行中" : "已停止")}");
            });
        }
        
        /// <summary>
        /// 刷新所有计算属性
        /// </summary>
        private void RefreshAllProperties()
        {
            OnPropertyChanged(nameof(StartServiceButtonText));
            OnPropertyChanged(nameof(IsStartServiceEnabled));
            OnPropertyChanged(nameof(IsStopServiceEnabled));
            OnPropertyChanged(nameof(ServiceStatusColor));
            OnPropertyChanged(nameof(ServiceDurationText));
            OnPropertyChanged(nameof(EstimatedNotificationsText));
        }

        #endregion

        #region 公共方法
        
        /// <summary>
        /// 页面出现时调用，同步服务状态
        /// </summary>
        public void OnPageAppearing()
        {
            SyncServiceStatus();
            _logManager.LogInfo("前台服务页面显示，已同步服务状态");
        }

        #endregion

        #region 资源释放

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            // 取消订阅服务状态变化事件
            _foregroundService.ServiceStateChanged -= OnServiceStateChanged;
            
            _updateTimer?.Stop();
            _updateTimer?.Dispose();
        }

        #endregion
    }
}